﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JuCloudy.Sys.App.AppInfo.controls
{
    public partial class DiaryEditor : UserControl
    {
        public DiaryEditor()
        {
            InitializeComponent();
            diaries = new ObservableCollection<DiaryEditorEntity>();
        }

        private ObservableCollection<DiaryEditorEntity> diaries;

        private void AddTitle()
        {
            if (diaries.Count > 0)
            {
                int index = diaries.OrderByDescending(p => p.Index).ToList()[0].Index;
                diaries.Add(new DiaryEditorEntity()
                {
                    Index = index + 1
                });
                this._titles.Items.Add(new TextBox() { Tag = index + 1 });
            }
            else
            {
                this._titles.Items.Add(new TextBox() { Tag = 0 });
            }
        }

        private void AddContent()
        {
            var query = this.diaries.First(p => p.Index == (int)((TextBox)this._titles.SelectedItem).Tag);
            if (query.Texts.Count > 0)
            {
                int index = (int)query.Texts.OrderByDescending(p => (int)p.Tag).ToList()[0].Tag;
                var text = new TextBox()
                {
                    Tag = index + 1
                };
                query.Texts.Add(text);
                text.TextChanged += (obj, e) =>
                {
                    ContentTextChange(obj, e);
                };
                this.contents.Items.Add(text);
            }
            else
            {
                var text = new TextBox()
                {
                    Tag = 0
                };

                query.Texts.Add(text);
                text.TextChanged += (obj, e) =>
                {
                    ContentTextChange(obj, e);
                };
                this.contents.Items.Add(text);
            }
        }

        private void ContentTextChange(object obj,TextChangedEventArgs e)
        {
            var query = this.diaries.First(p => p.Index == (int)((TextBox)this._titles.SelectedItem).Tag);
            var text = query.Texts.First(p => p.Tag == ((TextBox)obj).Tag);
            text.Text = ((TextBox)obj).Text;
        }

    }

    public class DiaryEditorEntity
    {
        public int Index { get; set; }

        public List<TextBox> Texts { get; set; }
    }
}
